<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { ElMessage } from 'element-plus'
import api from '@/api/request'
import { useUserStore } from '@/stores/useUserStore'
import { ChatDotRound } from '@element-plus/icons-vue'

const messages = ref([]) // 用于存储实时消息
const userStore = useUserStore() // 获取用户store
const wsConnection = ref(null) // WebSocket连接实例
const newMessage = ref('') // 用于存储新消息输入
const userId = ref(null) // 存储用户ID
const isConnected = ref(false) // 添加连接状态标志
const dialogVisible = ref(false) // 控制离线消息对话框的显示

// 存储离线消息
const offlineMessages = ref([])
const adminMessages = ref([])
const userMessages = ref([])

// 添加管理员列表
const adminList = ref([])
const selectedAdmin = ref(null)
// 存储已读消息ID
const readMessageIds = ref(new Set())
// 控制消息提示动画
const hasUnread = ref(false)

// 显示离线消息对话框
const showOfflineMessages = () => {
  dialogVisible.value = true
}

// 获取管理员列表
const fetchAdminList = async () => {
  try {
    const response = await api.post('/alladmin')
    if (response.data && response.data.code === 200) {
      adminList.value = response.data.data
      console.log('管理员列表:', adminList.value)
    }
  } catch (error) {
    console.error('获取管理员列表失败:', error)
    ElMessage.error('获取管理员列表失败')
  }
}

// 选择管理员
const selectAdmin = (admin) => {
  selectedAdmin.value = admin
}

// 格式化消息时间
const formatMessageTime = (timestamp) => {
  const date = new Date(timestamp)
  return date.toLocaleString()
}
// 标记所有消息为已读
const markAllAsRead = () => {
  offlineMessages.value.forEach((msg) => {
    readMessageIds.value.add(msg.id)
  })
  hasUnread.value = false
  ElMessage.success('所有消息已标记为已读')
}
// 更新未读状态
const updateUnreadStatus = () => {
  const unreadCount = offlineMessages.value.filter(
    (msg) => !readMessageIds.value.has(msg.id)
  ).length
  hasUnread.value = unreadCount > 0
}

// 修改获取离线消息的函数
const fetchOfflineMessages = async () => {
  try {
    const userId = userStore.userId
    if (!userId) {
      console.error('未找到用户ID')
      return
    }

    const response = await api.post(`/checkOfflineMessages2?userId=${userId}`)
    if (response.data.code === 200) {
      const data = response.data.data
      console.log('data', data)

      // 处理用户消息（data[0]和data[1]）
      const allUserMessages = [...(data[0] || []), ...(data[1] || [])]
      userMessages.value = allUserMessages.map((msg) => ({
        id: msg.id || `${msg.fromUserId}-${Date.now()}`,
        fromUserName: msg.fromUserName,
        content: msg.content,
        senderType: msg.senderType,
        fromUserId: msg.fromUserId,
        toUserId: msg.toUserId,
        timestamp: msg.timestamp || new Date().toISOString()
      }))

      // 处理管理员消息（data[2]）
      adminMessages.value = (data[2] || []).map((msg) => ({
        id: msg.id || `${msg.fromUserId}-${Date.now()}`,
        fromUserName: msg.fromUserName,
        content: msg.content,
        senderType: msg.senderType,
        fromUserId: msg.fromUserId,
        toUserId: msg.toUserId,
        timestamp: msg.timestamp || new Date().toISOString()
      }))

      // 合并所有消息
      offlineMessages.value = [...userMessages.value, ...adminMessages.value]

      // 更新未读状态
      updateUnreadStatus()
    } else {
      console.error('获取离线消息失败:', response.data.message)
    }
  } catch (error) {
    console.error('获取离线消息出错:', error)
  }
}

// 修改WebSocket连接管理
const connectWebSocket = async (id) => {
  if (!id) {
    console.error('未提供用户ID')
    return
  }

  try {
    if (wsConnection.value !== null) {
      console.log('已存在WebSocket连接，先关闭旧连接')
      wsConnection.value.close()
      isConnected.value = false
    }

    console.log('正在尝试建立WebSocket连接...')
    console.log('用户ID:', id)

    // 创建WebSocket连接
    const wsUrl = `ws://xvr8a0okpffe-7095.beijing-01.dayunet.com/ws?userId=${id}`
    console.log('WebSocket URL:', wsUrl)

    wsConnection.value = new WebSocket(wsUrl)

    // 连接建立时的处理
    wsConnection.value.onopen = () => {
      console.log('WebSocket连接成功建立')
      console.log('连接状态:', wsConnection.value.readyState)
      isConnected.value = true
      ElMessage.success('已连接到消息服务器')
    }

    // 接收消息的处理
    wsConnection.value.onmessage = (event) => {
      try {
        console.log('收到新消息:', event.data)
        const data = JSON.parse(event.data)
        console.log('解析后的消息数据:', data)

        // 只处理管理员发送的消息
        if (data.senderType === 'admin') {
          const newMessage = {
            id: data.fromUserId + '-' + Date.now(),
            fromUserId: data.fromUserId,
            fromUserName: data.fromUserName || '管理员',
            content: data.content || data.contents,
            timestamp: data.timestamp || new Date().toISOString(),
            senderType: 'admin'
          }

          messages.value.unshift(newMessage)

          // 如果消息不是自己发送的，显示通知
          if (data.fromUserId !== userId.value) {
            ElMessage({
              type: 'info',
              message: `收到来自 ${newMessage.fromUserName} 的新消息`,
              duration: 3000
            })
          }
        } else {
          console.log('忽略消息：非管理员发送的消息', data)
        }

        // 保持消息列表最多显示50条
        if (messages.value.length > 50) {
          messages.value = messages.value.slice(0, 50)
        }
      } catch (error) {
        console.error('处理WebSocket消息失败:', error)
        console.error('原始消息数据:', event.data)
      }
    }

    // 连接关闭的处理
    wsConnection.value.onclose = (event) => {
      console.log('WebSocket连接已关闭')
      console.log('关闭代码:', event.code)
      console.log('关闭原因:', event.reason)
      wsConnection.value = null
      isConnected.value = false
      ElMessage.warning('消息服务器连接已断开，请重新连接')
    }

    // 错误处理
    wsConnection.value.onerror = (error) => {
      console.error('WebSocket错误:', error)
      console.log('连接状态:', wsConnection.value?.readyState)
      ElMessage.error('消息服务器连接失败，请检查服务器状态')
      wsConnection.value = null
      isConnected.value = false
    }
  } catch (error) {
    console.error('创建WebSocket连接失败:', error)
    console.error('错误详情:', error.message)
    ElMessage.error('无法连接到消息服务器，请检查网络连接')
    wsConnection.value = null
    isConnected.value = false
  }
}

// 获取用户ID
const getId = async () => {
  try {
    const response = await api.post('/id')
    console.log('response', response)
    userId.value = response.data.data
    userStore.userId = response.data.data
  } catch (error) {
    console.error('获取用户ID失败:', error)
    ElMessage.error('获取用户ID失败')
  }
}

// 修改发送消息函数
const sendMessage = () => {
  if (!newMessage.value.trim()) {
    ElMessage.warning('请输入消息内容')
    return
  }

  if (!wsConnection.value || wsConnection.value.readyState !== WebSocket.OPEN) {
    ElMessage.error('未连接到消息服务器，请先建立连接')
    return
  }

  try {
    const messageData = {
      type: 'message',
      fromUserId: userId.value,
      fromUserName: userStore.name || '未知用户',
      content: newMessage.value.trim(),
      timestamp: new Date().toISOString(),
      senderType: 'user'
    }

    // 先添加到本地消息列表
    const localMessage = {
      id: userId.value + '-' + Date.now(),
      fromUserId: userId.value,
      fromUserName: userStore.name || '未知用户',
      content: newMessage.value.trim(),
      timestamp: new Date().toISOString(),
      senderType: 'user'
    }
    messages.value.unshift(localMessage)

    // 发送到服务器
    wsConnection.value.send(JSON.stringify(messageData))

    // 清空输入框
    newMessage.value = ''

    ElMessage({
      type: 'success',
      message: '消息发送成功',
      duration: 2000
    })

    if (messages.value.length > 50) {
      messages.value = messages.value.slice(0, 50)
    }
  } catch (error) {
    console.error('发送消息失败:', error)
    ElMessage.error('发送消息失败，请重试')
  }
}

// 连接 WebSocket，获取实时消息
onMounted(async () => {
  await getId()
  await fetchAdminList()
  // 初始获取离线消息
  await fetchOfflineMessages()
})

onBeforeUnmount(() => {
  if (wsConnection.value) {
    console.log('组件卸载，关闭WebSocket连接')
    wsConnection.value.close()
    wsConnection.value = null
  }
})
</script>

<template>
  <div class="chat-container">
    <!-- 离线消息图标 -->
    <div class="message-icon" @click="showOfflineMessages">
      <el-badge :hidden="!hasUnread" class="message-badge"> </el-badge>
    </div>

    <!-- 离线消息对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="离线消息"
      width="600px"
      class="offline-message-dialog"
    >
      <div class="dialog-content">
        <div class="message-header-bar">
          <div class="header-left">
            <span class="total-count">
              共 {{ offlineMessages.length }} 条消息 ({{
                adminMessages.length
              }}
              条系统消息, {{ userMessages.length }} 条用户消息)
            </span>
            <span class="unread-count" v-if="hasUnread">
              ({{
                offlineMessages.filter((msg) => !readMessageIds.has(msg.id))
                  .length
              }}
              条未读)
            </span>
          </div>
          <el-button
            type="primary"
            link
            @click="markAllAsRead"
            v-if="hasUnread"
          >
            全部标记为已读
          </el-button>
        </div>

        <el-tabs type="border-card">
          <el-tab-pane label="全部消息">
            <div class="messages-container">
              <template v-if="offlineMessages.length > 0">
                <div
                  v-for="message in offlineMessages"
                  :key="message.id"
                  class="message-item"
                  :class="{
                    'admin-message': message.senderType === 'admin',
                    'user-message': message.senderType === 'user',
                    unread: !readMessageIds.has(message.id)
                  }"
                >
                  <div class="message-header">
                    <div class="sender-info">
                      <el-avatar :size="32" class="sender-avatar">
                        {{ message.fromUserName.charAt(0).toUpperCase() }}
                      </el-avatar>
                      <span class="sender-name">{{
                        message.fromUserName
                      }}</span>
                      <el-tag
                        v-if="message.senderType === 'admin'"
                        size="small"
                        type="success"
                        effect="dark"
                      >
                        系统消息
                      </el-tag>
                      <el-tag v-else size="small" type="info" effect="plain">
                        用户消息
                      </el-tag>
                      <span
                        v-if="!readMessageIds.has(message.id)"
                        class="unread-marker"
                      >
                        新消息
                      </span>
                    </div>
                    <div class="message-actions">
                      <span class="message-time">
                        {{ new Date(message.timestamp).toLocaleString() }}
                      </span>
                    </div>
                  </div>
                  <div class="message-content">
                    {{ message.content }}
                  </div>
                </div>
              </template>
              <div v-else class="no-messages">
                <el-empty description="暂无消息" />
              </div>
            </div>
          </el-tab-pane>

          <el-tab-pane label="系统消息">
            <div class="messages-container">
              <template v-if="adminMessages.length > 0">
                <div
                  v-for="message in adminMessages"
                  :key="message.id"
                  class="message-item admin-message"
                  :class="{ unread: !readMessageIds.has(message.id) }"
                >
                  <div class="message-header">
                    <div class="sender-info">
                      <el-avatar :size="32" class="sender-avatar">
                        {{ message.fromUserName.charAt(0).toUpperCase() }}
                      </el-avatar>
                      <span class="sender-name">{{
                        message.fromUserName
                      }}</span>
                      <el-tag size="small" type="success" effect="dark">
                        系统消息
                      </el-tag>
                      <span
                        v-if="!readMessageIds.has(message.id)"
                        class="unread-marker"
                      >
                        新消息
                      </span>
                    </div>
                    <div class="message-actions">
                      <span class="message-time">
                        {{ new Date(message.timestamp).toLocaleString() }}
                      </span>
                    </div>
                  </div>
                  <div class="message-content">
                    {{ message.content }}
                  </div>
                </div>
              </template>
              <div v-else class="no-messages">
                <el-empty description="暂无系统消息" />
              </div>
            </div>
          </el-tab-pane>

          <el-tab-pane label="用户消息">
            <div class="messages-container">
              <template v-if="userMessages.length > 0">
                <div
                  v-for="message in userMessages"
                  :key="message.id"
                  class="message-item user-message"
                  :class="{ unread: !readMessageIds.has(message.id) }"
                >
                  <div class="message-header">
                    <div class="sender-info">
                      <el-avatar :size="32" class="sender-avatar">
                        {{ message.fromUserName.charAt(0).toUpperCase() }}
                      </el-avatar>
                      <span class="sender-name">{{
                        message.fromUserName
                      }}</span>
                      <el-tag size="small" type="info" effect="plain">
                        用户消息
                      </el-tag>
                      <span
                        v-if="!readMessageIds.has(message.id)"
                        class="unread-marker"
                      >
                        新消息
                      </span>
                    </div>
                    <div class="message-actions">
                      <span class="message-time">
                        {{ new Date(message.timestamp).toLocaleString() }}
                      </span>
                    </div>
                  </div>
                  <div class="message-content">
                    {{ message.content }}
                  </div>
                </div>
              </template>
              <div v-else class="no-messages">
                <el-empty description="暂无用户消息" />
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-dialog>

    <!-- 联系人列表 -->
    <div class="contacts-list">
      <div class="contacts-header">
        <h3>管理员列表</h3>
      </div>
      <div class="contacts-body">
        <div
          v-for="admin in adminList"
          :key="admin.id"
          class="contact-item"
          :class="{ active: selectedAdmin?.id === admin.id }"
          @click="selectAdmin(admin)"
        >
          <el-avatar :size="40" class="contact-avatar">
            {{ admin.username.charAt(0).toUpperCase() }}
          </el-avatar>
          <div class="contact-info">
            <div class="contact-name">{{ admin.username }}</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 聊天区域 -->
    <div class="chat-area">
      <div class="chat-header">
        <h3>系统消息</h3>
        <div class="websocket-controls">
          <el-button
            type="success"
            @click="connectWebSocket(userId)"
            :disabled="!userId"
          >
            {{ isConnected ? '已连接' : '建立WebSocket连接' }}
          </el-button>
          <div class="message-icon" @click="showOfflineMessages">
            <el-badge
              :value="
                offlineMessages.filter((msg) => !readMessageIds.has(msg.id))
                  .length
              "
              :hidden="!hasUnread"
              class="message-badge"
            >
              <el-icon
                :size="24"
                class="message-bell"
                :class="{ 'has-unread': hasUnread }"
              >
                <ChatDotRound />
              </el-icon>
            </el-badge>
          </div>
        </div>
      </div>

      <div class="messages-container">
        <div v-if="messages && messages.length > 0" class="messages-list">
          <div
            v-for="message in messages"
            :key="message.id"
            class="message"
            :class="{
              'message-sent': message.fromUserId === userId,
              'message-received': message.fromUserId !== userId,
              'admin-message': message.senderType === 'admin'
            }"
          >
            <div class="message-avatar">
              <el-avatar :size="40">
                {{ message.fromUserName.charAt(0).toUpperCase() }}
              </el-avatar>
            </div>
            <div class="message-content-wrapper">
              <div class="message-info">
                <span class="sender-name">{{ message.fromUserName }}</span>
                <el-tag
                  v-if="message.senderType === 'admin'"
                  size="small"
                  type="success"
                  effect="dark"
                >
                  系统消息
                </el-tag>
                <span class="message-time">
                  {{ formatMessageTime(message.timestamp) }}
                </span>
              </div>
              <div class="message-bubble">
                {{ message.content }}
              </div>
            </div>
          </div>
        </div>
        <div v-else class="no-messages">
          <el-empty description="暂无实时消息" />
        </div>
      </div>

      <!-- 消息输入区域 -->
      <div class="chat-input">
        <el-input
          v-model="newMessage"
          type="text"
          placeholder="输入消息..."
          @keyup.enter="sendMessage"
          :disabled="!isConnected"
          maxlength="500"
          show-word-limit
        >
          <template #append>
            <el-button
              type="primary"
              @click="sendMessage"
              :disabled="!isConnected || !newMessage.trim()"
            >
              发送
            </el-button>
          </template>
        </el-input>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.chat-container {
  display: flex;
  height: calc(100vh - 120px);
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  margin: 20px;
  overflow: hidden;
}

.contacts-list {
  width: 280px;
  border-right: 1px solid #e6e6e6;
  display: flex;
  flex-direction: column;

  .contacts-header {
    padding: 20px;
    border-bottom: 1px solid #e6e6e6;

    h3 {
      margin: 0;
      color: #333;
      font-size: 16px;
    }
  }

  .contacts-body {
    flex: 1;
    overflow-y: auto;
  }
}

.contact-item {
  display: flex;
  align-items: center;
  padding: 12px 20px;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;

  &:hover {
    background-color: #f5f7fa;
  }

  &.active {
    background-color: #ecf5ff;
  }

  .contact-avatar {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    margin-right: 12px;
  }

  .contact-info {
    flex: 1;

    .contact-name {
      font-size: 14px;
      color: #333;
      margin-bottom: 4px;
    }
  }
}

.chat-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: #f5f7fa;

  .chat-header {
    padding: 20px;
    background: #fff;
    border-bottom: 1px solid #e6e6e6;
    display: flex;
    justify-content: space-between;
    align-items: center;

    h3 {
      margin: 0;
      color: #333;
      font-size: 16px;
    }
  }

  .messages-container {
    flex: 1;
    padding: 20px;
    overflow-y: auto;
    display: flex;
    flex-direction: column;
  }

  .messages-list {
    display: flex;
    flex-direction: column-reverse;
    gap: 16px;
  }

  .message {
    display: flex;
    gap: 12px;
    padding: 8px;
    transition: all 0.3s ease;

    &.message-sent {
      flex-direction: row-reverse;

      .message-content-wrapper {
        align-items: flex-end;
      }

      .message-bubble {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border-radius: 16px 16px 0 16px;
      }
    }

    &.message-received {
      .message-bubble {
        background: #f0f2f5;
        color: #333;
        border-radius: 16px 16px 16px 0;
      }
    }

    &.admin-message {
      .message-bubble {
        background: linear-gradient(135deg, #4caf50 0%, #2e7d32 100%);
        color: white;
      }
    }

    .message-avatar {
      flex-shrink: 0;
    }

    .message-content-wrapper {
      display: flex;
      flex-direction: column;
      gap: 4px;
      max-width: 70%;
    }

    .message-info {
      display: flex;
      align-items: center;
      gap: 8px;
      font-size: 12px;
      color: #666;

      .sender-name {
        font-weight: 600;
        color: #333;
      }

      .message-time {
        color: #999;
      }
    }

    .message-bubble {
      padding: 12px 16px;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
      word-break: break-word;
      line-height: 1.5;
    }
  }

  .chat-input {
    padding: 20px;
    background: #fff;
    border-top: 1px solid #e6e6e6;

    :deep(.el-input__wrapper) {
      padding-right: 0;
      border-radius: 20px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }

    :deep(.el-input-group__append) {
      padding: 0;
      background-color: transparent;
      border: none;
    }

    .el-button {
      margin: 0;
      height: 40px;
      padding: 0 20px;
      border-radius: 0 20px 20px 0;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      border: none;

      &:hover {
        opacity: 0.9;
      }

      &:disabled {
        opacity: 0.7;
        cursor: not-allowed;
      }
    }
  }
}
.websocket-controls {
  display: flex;
  gap: 12px;
  align-items: center;

  .el-button {
    &.is-disabled {
      opacity: 0.7;
      cursor: not-allowed;
    }
  }

  .message-icon {
    cursor: pointer;
    position: relative;
    display: inline-block;
    margin-left: 8px;

    .message-bell {
      padding: 8px;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      border-radius: 50%;
      color: white;
      transition: all 0.3s ease;
      box-shadow: 0 4px 12px rgba(102, 126, 234, 0.25);

      &.has-unread {
        animation: pulse 2s infinite;
      }

      &:hover {
        transform: scale(1.1);
        box-shadow: 0 6px 16px rgba(102, 126, 234, 0.35);
      }
    }
  }
}

.no-messages {
  padding: 32px 0;
  display: flex;
  justify-content: center;
  align-items: center;
}
.message-badge {
  :deep(.el-badge__content) {
    background-color: #f56c6c;
    animation: bounce 1s infinite;
  }
}
// 消息图标样式
.message-icon {
  cursor: pointer;
  position: relative;
  display: inline-block;

  .message-badge {
    .message-bell {
      color: #909399;
      transition: color 0.3s;

      &.has-unread {
        color: #409eff;
        animation: bell-ring 1s ease-in-out;
      }
    }
  }
}

// 离线消息对话框样式
.offline-message-dialog {
  .dialog-content {
    padding: 0;
  }

  .message-header-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px;
    border-bottom: 1px solid #ebeef5;

    .header-left {
      .total-count {
        color: #606266;
        margin-right: 8px;
      }

      .unread-count {
        color: #f56c6c;
      }
    }
  }

  .messages-container {
    max-height: 500px;
    overflow-y: auto;
    padding: 16px;

    .message-item {
      padding: 16px;
      border-radius: 4px;
      margin-bottom: 16px;
      transition: all 0.3s;

      &.unread {
        background-color: #f0f9ff;
        border-left: 3px solid #409eff;
      }

      &.admin-message {
        border: 1px solid #e1f3d8;
        background-color: #f0f9eb;
      }

      &.user-message {
        border: 1px solid #ebeef5;
        background-color: #f5f7fa;
      }

      .message-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 12px;

        .sender-info {
          display: flex;
          align-items: center;
          gap: 8px;

          .sender-avatar {
            background-color: #409eff;
            color: white;
          }

          .sender-name {
            font-weight: 500;
            color: #303133;
          }

          .unread-marker {
            color: #f56c6c;
            font-size: 12px;
            padding: 2px 6px;
            border-radius: 10px;
            background-color: #fef0f0;
          }
        }

        .message-actions {
          .message-time {
            color: #909399;
            font-size: 12px;
          }
        }
      }

      .message-content {
        color: #606266;
        line-height: 1.5;
        white-space: pre-wrap;
      }
    }

    .no-messages {
      display: flex;
      justify-content: center;
      align-items: center;
      min-height: 200px;
    }
  }
}

// 动画
@keyframes bell-ring {
  0% {
    transform: rotate(0);
  }
  25% {
    transform: rotate(15deg);
  }
  50% {
    transform: rotate(-15deg);
  }
  75% {
    transform: rotate(15deg);
  }
  100% {
    transform: rotate(0);
  }
}
</style>
